package org.adream.account.util;

import java.security.MessageDigest;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.util.StringUtils;

/**
 * 密码操作类
 * 
 * @author sl
 *
 */
public class PasswordUtil {

	/**
	 * 生成含有随机盐的密码
	 */
	public static String generate(String password, String salt) {
		password = md5Hex(password + salt);
		return new String(password);
	}

	/**
	 * 校验密码是否正确
	 */
	public static boolean verify(String password, String salt, String md5) {
		return md5Hex(password + salt).equals(md5);
	}

	/**
	 * 获取十六进制字符串形式的MD5摘要
	 */
	public static String md5Hex(String src) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] bs = md5.digest(src.getBytes());
			return new String(Hex.encode(bs));
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 验证用户密码
	 * @param password  用户输入的密码
	 * @param salt	盐
	 * @param method	加密方式
	 * @param oriPwd	原始密码
	 * @return
	 */
	public static boolean verifyPwd(String password, String salt, String method, String oriPwd) {
		boolean isValid = false;
		if (StringUtils.isEmpty(method) || StringUtils.isEmpty(oriPwd)) {
			return isValid;
		} else {
			switch (method) {
			case "M": //mis
				isValid = oriPwd.equals(generate(salt, password));
				break;
			case "B": //adreambox
				isValid = oriPwd.equals(generate(md5Hex(password), salt));
				break;
			case "A": //account
			default:
				isValid = oriPwd.equals(generate(password,salt));				
			}
			return isValid;
		}
	}
}